package com.tanhua.sso.controller;

import com.tanhua.sso.service.SmsService;
import com.tanhua.sso.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @Author YuShiLong
 * @Date 2021/4/11 18:42
 * @Version 1.0
 */
@RestController
@RequestMapping("user")
@Slf4j
public class SmsController {

    @Autowired
    private SmsService smsService;


    /**
     * 发送短信验证码接口
     * @param param
     * @return
     */
    @RequestMapping("login")
    public ResponseEntity<ErrorResult> sendCheckCode(@RequestBody Map<String, String> param) {
        ErrorResult errorResult = null;
        //获取前端传来的json数据中的手机号
        String phone = param.get("phone");
        //调用业务层方法,发送验证码
        try {
            errorResult = smsService.sendCheckCode(phone);
            //不为空,代表发送成功
            if (null == errorResult) {
                //发送成功,像前端返回一个null
                return ResponseEntity.ok(null);
            }
        } catch (Exception e) {
            //发送失败,记录日志
            log.error("发送短信验证码失败~ phone = " + phone, e);
            //设置失败的响应体
            errorResult = ErrorResult.builder().errCode("000002").errMessage("短信验证码发送失败!").build();
        }
        //发送失败,向前端返回失败的响应
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
    }
}
